import msg
import Image, ImageDraw, ImageFilter
import MySQLdb
import gtk
clipboard = gtk.clipboard_get()

#4: {11:(19, 14), 12:(19, 19), 13:(20, 23), 14:(14, 25), 15:(8, 24)}
townPositions = {
	1: {0:(34,10), 1:(28,12), 2:(22,15), 3:(17,19), 4:(17,23), 5:(16,29), 6:(21,28), 7:(26,30), 8:(33,33), 9:(38,36), 10:(42,33), 11:(49,33), 12:(53,31), 13:(57,29), 14:(63,25), 15:(61,20), 16:(60,15), 17:(55,16), 18:(56,20), 19:(55,24)},
	2: {0:(23,13), 1:(22,7), 2:(29,7), 3:(38,5), 4:(45,6), 5:(50,7), 6:(54,9), 7:(58,11), 8:(58,16), 9:(56,21), 10:(54,26), 11:(50,28), 12:(40,29), 13:(35,29), 14:(26,28), 15:(17,28), 16:(15,23), 17:(9,22), 18:(9,17), 19:(14, 14)},
	3: {0:(36,6), 1:(30,5), 2:(26,6), 3:(22,9), 4:(17,12), 5:(12,18), 6:(12,23), 7:(17,26), 8:(22,28), 9:(26,30), 10:(30,32), 11:(35,33), 12:(40,31), 13:(43,26), 14:(55,29), 15:(52,25), 16:(62,19), 17:(61,14), 18:(57,11), 19:(51,8)},
	4: {0:(38,9), 1:(43,10), 2:(50,11), 3:(54,14), 4:(58,17), 5:(50,20), 6:(45,21), 7:(40,21), 8:(36, 18), 9:(32,15), 10:(25,15), 11:(19,17), 12:(20,21), 13:(21,25), 14:(16,26), 15:(10,25), 16:(8, 20), 17:(13,15), 18:(19,12), 19:(27, 10)},
	5: {0:(17,16), 1:(18,11), 2:(23,7), 3:(30,5), 4:(39,5), 5:(39,9), 6:(46,9), 7:(52,9), 8:(54,13), 9:(60,14), 10:(62,19), 11:(58,24), 12:(53,26), 13:(47,28), 14:(42,31), 15:(33,34), 16:(28,31), 17:(23,28), 18:(46,23), 19:(45,18)},
	6: {0:(34,27), 1:(42,31), 2:(49,33), 3:(55,34), 4:(61,32), 5:(61,27), 6:(56,25), 7:(51, 23), 8:(47,15), 9:(43,13), 10:(36,10), 11:(31,11), 12:(26,13), 13:(20,15), 14:(15,17), 15:(9, 21), 16:(12, 24), 17:(17, 27), 18:(14,32), 19:(20, 34)},
	7: {0:(12,19), 1:(10,16), 2:(9,13), 3:(9,10), 4:(13,8), 5:(17,9), 6:(24,12), 7:(29,13), 8:(36,14), 9:(32,16), 10:(34,19), 11:(37,22), 12:(37,26), 13:(32,29), 14:(32,35), 15:(28,33), 16:(23,32), 17:(18,34), 18:(14,31), 19:(10,30)},
	8: {0:(42,18), 1:(46,20), 2:(50,22), 3:(55,25), 4:(51,27), 5:(47,29), 6:(43,30), 7:(36,33), 8:(32,33), 9:(24,32), 10:(19,29), 11:(14,25), 12:(10,23), 13:(10,19), 14:(8,15), 15:(11,13), 16:(14,11), 17:(17,9), 18:(23,9), 19:(26,13)},
	9: {0:(15,23), 1:(9,22), 2:(10,17), 3:(14,13), 4:(25,7), 5:(30,4), 6:(37,5), 7:(43,10), 8:(59,14), 9:(63,17), 10:(62,22), 11:(53,29), 12:(48,31), 13:(44,27), 14:(39,28), 15:(40,32), 16:(32,32), 17:(28,33), 18:(26,29), 19:(24,26)},
	10:{0:(41,12), 1:(46,8), 2:(52,8), 3:(57,12), 4:(61,17), 5:(59,23), 6:(54,26), 7:(49,29), 8:(39,30), 9:(31,32), 10:(26,31), 11:(21,29), 12:(16,27), 13:(10,22), 14:(11,13), 15:(16,9), 16:(24,8), 17:(29,11), 18:(28,15), 19:(20,15)}
}

def show(ocean, lowerLimit=500, *players):
	x = ocean[0:1]; y = ocean[1:2]
	msg.show('-'*40, 'black', 1)
	msg.show('Ocean {0} Map'.format(x + y), 'yellow')
	msg.show(' ({0} treshold)'.format(lowerLimit), 'black', True)
	
	conn = MySQLdb.connect(host='localhost', user='root', passwd='', db='defcon')
	sql = 'SELECT * FROM islands WHERE x > {0}95 and x < {1}99 and y > {2}95 and y < {3}99'.format(int(x)-1, x, int(y)-1, y)
	conn.query(sql)
	islands = conn.store_result().fetch_row(maxrows=0)
	
	im = Image.new('RGBA', (1000, 1000), '#13467E') #03265E
	draw = ImageDraw.Draw(im)
	
	i, r = [0], [0]
	for n in range(1, 16):
		i.append(Image.open('img/island{0}.png'.format(n)))
		i[-1] = i[-1].convert('RGBA')
		r.append(i[-1].resize((i[-1].size[0]/14, i[-1].size[1]/14)))
	
	msg.show('Generating islands...', 'green')
	for counter, island in zip(range(len(islands)), islands):
		ix = (int(island[1]) - int(x) * 100) * 10
		iy = (int(island[2]) - int(y) * 100) * 10
		it = island[3]
		# Island Pictures
		if it < 16 and 1==2:
			im.paste(r[it], (ix, iy, ix+r[it].size[0], iy+r[it].size[1]), r[it])
		# Outlines
		if it <= 10:
			points = []
			for point in townPositions[it]:
				points.append((ix+2+townPositions[it][point][0], iy+2+townPositions[it][point][1]))
			draw.polygon(points, fill='#13567E') #03365E
		msg.show('\rGenerating islands...'); msg.show(' {0}%'.format(int(float(counter) / len(islands) * 100)), 'green', bold=True)
	msg.show('\rGenerating islands...'); msg.show(' DONE', 'green', 1, bold=True)

	msg.show('Generating towns...')
	for counter, island in zip(range(len(islands)), islands):
		drawTowns(draw, island, (x, y), 1, lowerLimit, *players)
		msg.show('\rGenerating towns...'); msg.show(' {0}%'.format(int(float(counter) / len(islands) * 100)), 'green', bold=True)
	msg.show('\rGenerating towns...'); msg.show(' DONE', 'green', 1, bold=True)
	
	msg.show('(press Esc to close the map window)', 'black', 1)
	msg.show('-'*40, 'black', 1)
	
	im.show()
	conn.close()
	
	msg.show('Type a filename (without extension) to save the image to, leave blank to skip.', 'blue', True);
	filename = raw_input('filename: ')
	if filename != '':
		im.save('/home/bruno/Dropbox/Public/games/grepolis/' + filename + '.png')
		clipboard.set_text('http://dl.dropbox.com/u/121630/games/grepolis/' + filename + '.png')
		msg.show('http://dl.dropbox.com/u/121630/games/grepolis/' + filename + '.png', 'black', True)
		msg.show('Public URL on the clipboard', 'blue', True)

def drawTowns(draw, island, ocean_xy, n, lowerLimit, *players):
	x, y = ocean_xy
	
	it = island[3]
	ix = (int(island[1]) - int(x) * 100) * 10
	iy = (int(island[2]) - int(y) * 100) * 10
	
	if it <= 10:
		conn = MySQLdb.connect(host='localhost', user='root', passwd='', db='defcon')
		sql = 'SELECT t.number_on_island, t.player_id, p.alliance_id, t.points, p.name, t.name'
		sql = sql + ' FROM towns t LEFT JOIN players p ON (t.player_id = p.id)'
		sql = sql + ' WHERE t.island_x = {0} and t.island_y = {1}'.format(island[1], island[2])
		conn.query(sql)
		towns = conn.store_result().fetch_row(maxrows=0)
		for town in towns:
			if town[3] < int(lowerLimit): continue
			pos = town[0]
			tx = ix + townPositions[it][pos][0]
			ty = iy + townPositions[it][pos][1]
			
			# Delta
			if town[2] == 32: outline = '#090'; fill = '#0F0' # Disciples of Ares
			
			# Full allies
			elif town[2] == 11862: outline = '#060'; fill = '#0C0' # Initiates of Ares (DoA academy)
			elif town[2] == 44: outline = '#060'; fill = '#0C0' # The Huns
			
			# NAPS
			elif town[2] == 2385: outline = '#030'; fill = '#0C0' # Black
			elif town[2] == 12945: outline = '#030'; fill = '#0C0' # Ravens (Black academy)
			elif town[2] == 10095: outline = '#030'; fill = '#0C0' # Asylum
			elif town[2] == 13811: outline = '#030'; fill = '#0C0' # Off Topic Crusaders
			
			# Open fire
			elif town[2] == 4182: outline = '#630'; fill = '#C90' # The Forgotten Phoenix
			
			# Declared enemies
			elif town[2] == 14311: outline = '#900'; fill = '#F00' # Final Sovereignty
			elif town[2] == 14728: outline = '#900'; fill = '#F00' # Legion of Chaos
			elif town[2] == 14865: outline = '#900'; fill = '#F00' # Eaters of the Dead
			elif town[2] == 971: outline = '#900'; fill = '#F00' # Imperium Magnus
			elif town[2] == 15043: outline = '#900'; fill = '#F00' # The God-Kings
			elif town[2] == 5237: outline = '#900'; fill = '#F00' # Rainmaker
			
			# Alliances Kappa
			#if town[2] == 168: outline = 'green'; fill = 'lime' # The Heirs of Artemis
			#elif town[2] == 305: outline = '#600'; fill = '#A00' # IX Legion
			
			# Misc
			elif town[1] == 0: outline = '#555'; fill = '#AAA' # abandoned
			else: outline = '#300'; fill = '#600' # others
			
			if outline:
				draw.rectangle([(tx, ty), (tx+3, ty+3)], outline)
				draw.rectangle([(tx+1, ty+1), (tx+2, ty+2)], fill)
			
			# Player
			targetIDs = []
			for player in players:
				targetIDs.append(player)
			for playerId in targetIDs:
				if town[1] == playerId or town[4] == playerId:
					draw.ellipse([(tx-5, ty-5), (tx+9, ty+9)], outline='#0C0')
					draw.text((tx+22, ty-40), town[4].replace('+', ' '), fill='#0C0')
					draw.text((tx+22, ty-30), town[5].replace('+', ' '), fill='#0A6')
					draw.line([(tx+7, ty-4), (tx+20, ty-30)], fill='#0C0')
					draw.line([(tx+20, ty-30), (tx+30, ty-30)], fill='#0C0')

def islandView():
	im = Image.open('img/island8.png')
	rs = im.resize((im.size[0]/14, im.size[1]/14), Image.ANTIALIAS)
	rs = rs.convert('RGBA')
	draw = ImageDraw.Draw(rs)
	
	for pos in range(0, 20):
		try:
			x = townPositions[8][pos][0]
			y = townPositions[8][pos][1]
		except:
			continue
		draw.rectangle([(x, y), (x+3, y+3)], '#660000')
		draw.rectangle([(x+1, y+1), (x+2, y+2)], '#FF6600')
	
	rr = rs.resize((rs.size[0]*3, rs.size[1]*3))
	rr.show()

if __name__ == "__main__":
    islandView()
